package com.tale.springbootatm.common.util;

import com.tale.springbootatm.common.vo.MessageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * author: 蔡奇峰
 * date: 2020/5/2 13:03
 **/
@Component
@Slf4j
public class MailUtil {
    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.from}")
    private String from;


    /**
     * 发送修改密码邮件
     *
     * @param msg
     */
    public void sendUpdatePwd(MessageVO msg) {
        if (ObjectUtils.isEmpty(msg)) {
            return;
        }
        // 卡号设置密文
        String card = msg.getBankCard() + "";
        int len = card.length();
        int middle = len % 2 == 0 ? (len / 2) - 1 : len / 2;
        card = card.substring(0, middle) + "***" + card.substring(middle + 3);

        // 密码加 * ，不能明文显示
        String password = msg.getPassword();
        password = "a" + password + "0";

        String subject = "中国建设银行";
        String to = msg.getMail();
        System.out.println("to-->" + to);

        String content = "<p>您的中国建设银行卡号:" + card + " 密码已经修改成功，如果不是" +
                "本人操作请到银行柜台修改  <!-- " + password + " ---> </p>";

        System.out.println("content-->" + content);

        //获取MimeMessage对象
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        try {
            messageHelper = new MimeMessageHelper(message, true);
            //邮件发送人
            messageHelper.setFrom(from);
            //邮件接收人
            messageHelper.setTo(to);
            //邮件主题
            message.setSubject(subject);
            //邮件内容，html格式
            messageHelper.setText(content, true);
            //发送
            mailSender.send(message);
            //日志信息
            log.info("邮件已经发送 ^_^ ~_~ ");
        } catch (MessagingException e) {
            log.error("发送邮件时发生异常！", e);
        }
    }

}
